package cn.edu.glut.repository;

import java.util.Collection;
import java.util.Iterator;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;

/**
 * 
 * @author Caizhfy
 * @version v.0.1
 * @createTime 2017年12月12日下午8:43:32
 * @email Caizhfy@163.com
 * @description 基础实现
 *
 */
public abstract class AbstractBatchRepository<T> implements BatchRepository<T> {
	
	@PersistenceContext
	protected EntityManager entityManager;
	
	@Transactional
	@Override
	public void batchInsert(Collection<T> collection) {
		int count = 0;
		Iterator<T> it = collection.iterator();
		while(it.hasNext()){
			entityManager.persist(it.next());
			count ++;
			if(count%30 == 0){
				entityManager.flush();
				entityManager.clear();
			}
		}
	}

	@Override
	public void batchUpdate(Collection<T> collection) {
		int count = 0;
		Iterator<T> it = collection.iterator();
		while(it.hasNext()){
			entityManager.merge(it.next());
			count ++;
			if(count%30 == 0){
				entityManager.flush();
				entityManager.clear();
			}
		}
	}
	
}
